<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/20
 * Time: 11:28
 */

namespace common\helpers;

use common\consts\Consts;
use yii\db\ActiveQuery;
use yii\db\QueryInterface;

class ExcelHelper
{
    /**
     * @param $filename string
     * @param $query ActiveQuery|QueryInterface
     * @param $format array
     */
    public static function exportToCsv($filename, $query, $format){
        if (StringUtil::isNullOrWhiteSpace($filename)){
            $filename = 'Csv_'.DateHelper::getCurrentDateTime();
        }

        header("Content-Type: application/csv");
        header("Charset=UTF-8");
        header("Content-Disposition: attachment; filename=$filename");
        $output = fopen('php://output', 'a') or die("Can't open php://output");
        //fputs($output, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));
        $title = [];
        foreach ($format as $item) {
            $title[] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $item['label']);
        }

        fputcsv($output, $title);
        $cnt = 0;
        $limit = 10000;
        foreach ($query->each(Consts::DEFAULT_PAGE_SIZE) as $query_item) {
            $cnt++;
            if ($limit == $cnt) { //刷新一下输出buffer，防止由于数据过多造成问题
                ob_flush();
                flush();
                $cnt = 0;
            }

            $row = [];
            foreach ($format as $item) {
                $formatFunction = $item['value'];
                if (is_string($formatFunction)) {
                    $value = $query_item[$formatFunction];
                } else {
                    $value = $formatFunction($query_item);
                }
                $row[] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $value);
                //$row[] = $value;
            }

            fputcsv($output, $row);
            unset($row);
        }

        fclose($output);
    }
}